#include "Insect.h"
#include "EcoSystem.h"
#include "Environment.h"
#include<iostream>

Insect::Insect(EcoSystem *eco_system) : Consumer(eco_system)
{
    set_alive();
    set_max_hp(1998);
    set_hp(get_max_hp() / 2);
    set_init_speed(3.0);
    set_speed(get_init_speed());
    set_life_span(LIFE_SPAN[get_species_id()] * (1 + max(min(0.2, EcoSystem::random_double() - 0.5), -0.2)));
}

Insect::~Insect() {}

const unsigned int Insect::get_species_id() const
{
    return INSECT_SPECIES_ID;
}


Gdiplus::Image *Insect::get_entity_image() const
{
    static Gdiplus::Image *img_lu = Gdiplus::Image::FromFile(L".\\images\\insect_lu.png");
    static Gdiplus::Image *img_ru = Gdiplus::Image::FromFile(L".\\images\\insect_ru.png");
    static Gdiplus::Image *img_ld = Gdiplus::Image::FromFile(L".\\images\\insect_ld.png");
    static Gdiplus::Image *img_rd = Gdiplus::Image::FromFile(L".\\images\\insect_rd.png");

    bool is_go_left = (get_position() - get_prev_position()).x < 0;
    bool is_go_up = (get_position() - get_prev_position()).y < 0;
    if (is_go_left && is_go_up)
        return img_lu;
    else if (!is_go_left && is_go_up)
        return img_ru;
    else if (is_go_left && !is_go_up)
        return img_ld;
    else
        return img_rd;
}

Entity *Insect::new_entity() const
{
    return new Insect(eco_system);
}

void Insect::on_tick()
{
    set_age(get_age() + 1);

    if (get_age() > get_life_span())
        set_dead();

    set_hp(get_hp() -  0.08 *get_speed() * get_speed() / 2);
    if (hungry()>0.9 && EcoSystem::random_double() < 0.1 && get_age()< get_life_span()*0.6)
    {
        multiply();
        set_hp(get_max_hp() / 2);
    }
    if (!avoid_predator(get_init_speed()))
    if (!prey(get_init_speed()))
        random_motion(get_init_speed()*0.5);

    /*if (go_left())
        is_go_left = true;
    else
        is_go_left = false;

    if (go_up())
        is_go_up = true;
    else
        is_go_up = false;*/


    Environment *ptr = eco_system->get_environment_instance();
    if (ptr->get_temperature() > 30.0 || ptr->get_temperature() < 5.0){
        set_hp(get_hp()*0.8);
    }

    if (ptr->get_rainfall() > 0.7)
        set_hp(get_hp()*0.6);
    
}

int    Insect::get_cost_of_being_preyed() const
{
    return get_hp()*0.1;
}
int    Insect::get_gain_after_being_preyed() const
{
    return get_hp()*0.3;
}